package com.diamond.smart.data.handler;

import com.alibaba.fastjson.JSON;
import com.diamond.smart.data.entity.VoltageDataEntity;
import com.diamond.smart.data.service.VoltageDataService;
import com.diamond.smart.data.vo.DiamondVo;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@EnableAsync //开启异步任务功能 线程池相关属性可以在配置文件中配置 spring.task.execution
@Slf4j
public class MqttHandler implements MqttCallback {

    /**
     * 断开连接后的回调
     *
     * @param cause
     */
    @SneakyThrows //所有异常都往外抛
    @Override
    public void connectionLost(Throwable cause) {

    }

    /**
     * 订阅主题的消息到达后的回调
     *
     * @param topic
     * @param message
     * @throws Exception
     */
    @Async
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String json = new String(message.getPayload());
        String[] split = topic.split("/");
        VoltageDataEntity dataEntity;
        if (split[2].equals("6")) {
            DiamondVo diamondVo = JSON.parseObject(json, DiamondVo.class);
            dataEntity = new VoltageDataEntity();
            dataEntity.setDeviceId(split[4].substring(2));
            dataEntity.setDataTime(new Date());
            dataEntity.setUnPro(diamondVo.getI1());
            dataEntity.setPro(diamondVo.getI2());
            dataEntity.setEast(diamondVo.getI3());
            dataEntity.setSouth(diamondVo.getI4());
            dataEntity.setPower(diamondVo.getPower());
        } else {
            dataEntity = JSON.parseObject(json, VoltageDataEntity.class);
            dataEntity.setDeviceId(split[2]);
            dataEntity.setDataTime(new Date());
        }
        SaveData.saveData.saveVoltageData(dataEntity);
        log.info("接收到来自{}的消息：{}", topic, json);
    }

    /**
     * 消息发送成功的回调
     *
     * @param token
     */
    @Async
    @SneakyThrows
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("消息：{}发送成功!", new String(token.getMessage().getPayload()));
    }

    /**
     * MqttCallBack无法注入依赖，折中办法
     */
    @Component
    public static class SaveData {

        @Autowired
        VoltageDataService dataService;

        private static SaveData saveData;  //必须要重写一下！！

        @PostConstruct
        public void init() {
            saveData = this;
            saveData.dataService = this.dataService;    //改成你们对应的Dao层
        }

        public boolean saveVoltageData(VoltageDataEntity dataEntity) {        //把Dao层的操作封装成一个方法
            return dataService.save(dataEntity);
        }
    }

    /**
     * 判断设备类型
     *
     * @param name
     * @return
     */
    public String whichType(String name) {
        String type = "";
        switch (name) {
            case "voltage":
                type = "杂散电流";
                break;
            default:
                type = "未知";
                break;
        }
        return type;
    }
}
